<template>
  <div class="page-importsetting">
    <Form class="import-form" label-position="top">
      <FormItem label="数据类型">
        <Select :value="type" @on-change="changeType">
          <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </FormItem>

      <FormItem label="路径选择" class="input-file">
        <Input :value="fileUrl" placeholder="请选择路径" style="display:none"/>
        <Input :value="fileName" placeholder="请选择路径" disabled/>
        <i class="iconfont icon-file" @click="changeType"/>
      </FormItem>

      <template v-if="type==='ds'">
        <FormItem label="数据筛选">
          <Button
            type="primary"
            @click="selectDataHandler(1)"
          >{{fields.length > 0 ? `已选择${fields.length}个字段` : '选择字段'}}</Button>
        </FormItem>

        <FormItem label>
          <Button
            type="primary"
            @click="selectDataHandler(2)"
          >{{dataFilter.rules.length > 0 ? `已添加${dataFilter.rules.length}个过滤条件` : '数据过滤'}}</Button>
        </FormItem>

        <FormItem label="导入数据到" v-if="fileUrl">
          <div class="import-to">/workspace/ds/{{fileUrl}}</div>
        </FormItem>
      </template>
    </Form>

    <!-- 选择结构数据 -->
    <Modal footer-hide title="选择数据集数据" v-model="dsdataVisible" width="1200px">
      <dsdata
        :fileUrl="fileUrl"
        v-if="dsdataVisible"
        @cancelHandler="dsdataVisible=false"
        @okHandler="dsdataOkHandler"
      />
    </Modal>

    <!-- 选择字段 -->
    <Modal footer-hide title="选择字段" v-model="selectdataVisible" width="700px">
      <select-data
        :id="fileUrl"
        :fields="fields"
        v-if="selectdataVisible"
        @cancelHandler="selectdataVisible=false"
        @okHandler="selectDataOk"
      />
    </Modal>

    <!-- 数据过滤 -->
    <Modal footer-hide title="数据过滤" v-model="filterdataVisible" width="700px">
      <data-filter
        :dataFilter="dataFilter"
        :fields="fields"
        :id="fileUrl"
        v-if="filterdataVisible"
        @cancelHandler="filterdataVisible=false"
        @okHandler="filterDataOk"
      />
    </Modal>

    <!-- 选择图谱数据 -->
    <Modal footer-hide title="选择图谱数据" v-model="ceptdataVisible" width="800px" class="cept-workflow-modal">
      <ceptdata
        :fileUrl="fileUrl"
        :hidePreview="true"
        v-if="ceptdataVisible"
        @cancelHandler="ceptdataVisible=false"
        @okHandler="ceptdataOkHandler"
      />
    </Modal>
  </div>
</template>

<script>
import { wfCode } from 'assets/scripts/code';
import SelectData from '../Common/SelectData';
import DataFilter from '../Common/DataFilter';
import Dsdata from '../Common/Dsdata';
import Ceptdata from '../Common/Ceptdata';

import { mapState, mapMutations } from 'vuex';
import { updateCustomNode } from 'http/api/workflow';

export default {
  props: ['nodeInfo'],
  components: {
    SelectData,
    DataFilter,
    Dsdata,
    Ceptdata
  },
  watch: {
    nodeInfo () {
      this.setNodeInfo();
    }
  },

  computed: {
    ...mapState({
      currentNode: state => state.workflow.currentNode,
      link: state => state.workflow.link,
      node: state => state.workflow.node
    })
  },

  data () {
    return {
      name: '',
      // 数据类型
      type: '',
      typeList: [
        {
          label: '数据集数据',
          value: 'ds'
        },
        {
          label: '图谱数据',
          value: 'cept'
        }
      ],
      // 路径选择
      fileUrl: '',
      fileName: '',
      selectdataVisible: false,
      filterdataVisible: false,
      dsdataVisible: false,
      ceptdataVisible: false,
      pipelineId: '',

      // 请求参数
      dataSourceId: null,
      fields: [],
      dataFilter: {
        condition: '',
        rules: []
      } // 数据过滤
    };
  },

  methods: {
    ...mapMutations(['setNode', 'setAutoDatas']),

    // 重置编辑信息
    setNodeInfo () {
      let { argValues, name } = this.nodeInfo;
      this.name = name;
      if (argValues) {
        argValues = JSON.parse(argValues);
        let { dataFilter, dataSourceId, fields } = argValues;
        // fields改造
        this.fields = [];
        fields.forEach(item => {
          this.fields.push({
            name: item
          });
        });

        // dataSourceId改造
        if (dataSourceId) {
          this.type = dataSourceId.type;
          this.fileUrl = dataSourceId.id;
          this.fileName = dataSourceId.name;

          if (this.fileUrl) {
            this.setAutoDatas(`/workspace/ds/${this.fileUrl}`);
          }
        }

        this.dataFilter = dataFilter;
      }
    },

    // 选择数据
    selectDataHandler (type) {
      if (!this.fileUrl) {
        this.$Message.error('请先选择或输入路径');
        return;
      }

      type === 1
        ? (this.selectdataVisible = true)
        : (this.filterdataVisible = true);
    },

    // 选中字段后
    selectDataOk (fields) {
      this.fields = fields;
      this.selectdataVisible = false;
      this.updateNodeInfo();
    },

    // 过滤字段
    filterDataOk (dataFilter) {
      this.dataFilter = dataFilter;
      this.filterdataVisible = false;
      this.updateNodeInfo();
    },

    // 选择数据
    dsdataOkHandler ({ id, name }) {
      if (this.fileUrl === id) {
        this.dsdataVisible = false;
        return;
      }

      this.fileUrl = id;
      if (this.fileUrl) {
        this.setAutoDatas(`/workspace/ds/${this.fileUrl}`);
      }
      this.fileName = name;
      this.dsdataVisible = false;
      // 清空字段
      this.fields = [];
      this.dataFilter = {
        condition: '',
        rules: []
      };

      this.importChange(id, 'fileUrl');
    },

    // 选择图谱数据后
    ceptdataOkHandler ({ id, name }) {
      if (this.fileUrl === id) {
        this.ceptdataVisible = false;
        return;
      }
      this.fileUrl = id;
      if (this.fileUrl) {
        this.setAutoDatas(`/workspace/ds/${this.fileUrl}`);
      }
      this.fileName = name;
      this.ceptdataVisible = false;

      this.importChange(id, 'fileUrl');
    },

    // 数据类型选择
    changeType (v) {
      let type = typeof v === 'string' ? v : this.type;

      if (!type) {
        this.$Message.error('请选择数据类型');
        return;
      }
      // 数据结构
      if (type === 'ds') {
        this.dsdataVisible = true;
      }

      if (type === 'cept') {
        this.ceptdataVisible = true;
      }

      this.type = type;

      // 数据清空
      if (typeof v === 'string') {
        this.fileUrl = '';
      }
    },

    // 输入更改
    importChange (e, name) {
      let nodeName = e.target && e.target.nodeName;
      let value;
      if (nodeName === 'INPUT') {
        value = e.target.value;

        value = value.trim();
        if (value === '') {
          return;
        }
      } else {
        value = e;
      }

      this[name] = value;
      if (
        (name === 'type' && this.fileUrl) ||
        (name === 'fileUrl' && this.type)
      ) {
        this.updateNodeInfo();
      }
    },

    /**
     * 输入数据的参数argValues
     * 请求更新节点的接口
     */
    updateNodeInfo () {
      let { x, y, id } = this.currentNode;
      let fields = [];

      if (this.fields.length) {
        this.fields.forEach(item => {
          fields.push(item.name);
        });
      }

      let obj = {
        dataSourceId: {
          type: this.type,
          id: this.fileUrl,
          name: this.fileName
        },
        dataFilter: this.dataFilter,
        fields: fields
      };
      let param = {
        id: id,
        location: { x, y },
        pipeline: {
          id: this.pipelineId
        },
        argValues: JSON.stringify(obj)
      };

      let wires = [];
      this.link.forEach(item => {
        let { start, end, srcIndex, desIndex } = item;
        if (start === id) {
          wires.push({
            srcId: start,
            desId: end,
            desIndex: desIndex || 0,
            srcIndex: srcIndex || 0
          });
        }
      });

      param.wires = wires;
      param.pipelineTaskNodeType = wfCode.IMPORT;

      // 先改数据
      this.node[id] = Object.assign({}, this.node[id], param);
      this.setNode(this.node);

      updateCustomNode(param).then(res => {
        this.node[id] = Object.assign({}, this.node[id], res.data);
        this.setNode(this.node);
      });
    }
  },

  mounted () {
    this.pipelineId = this.$route.query.pipelineId;

    // 节点编辑信息
    if (this.nodeInfo) {
      this.setNodeInfo();
    }
  }
};
</script>

<style rel="stylesheet/less" lang="less" scoped>
.page-importsetting {
  padding: 2px 0;
  .import-form {
    margin-top: 20px;
    padding-left: 20px;
    padding-right: 20px;
    min-height: 450px;
  }
  .view-btns {
    float: right;
    padding-right: 10px;
  }
  .import-to {
    width: 100%;
    word-break: break-all;
  }
}
</style>
